package com.winway.sixbook.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.winway.sixbook.HomeActivity;
import com.winway.sixbook.R;
import com.winway.sixbook.custom.ListViewAdapter;
import com.winway.sixbook.service.RecordDataManager;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;

public class TodayListNewActivity extends Activity implements OnChildClickListener{
	
	private static final String TAG = "TodayListNewActivity";
	RecordDataManager recordDataManager ;
	private DisplayMetrics dm;
	private ImageButton top_tbn_fanhui;
	private Button top_tbn_xinzeng;
	private TextView title;
	private Button navigate_btn_export;
	
	ProgressDialog pd=null;
	AlertDialog ad=null,ad1=null;
	AlertDialog.Builder builder=null,builder1=null;
	TextView tv=null;
	Calendar c=Calendar.getInstance();

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_today_list_new);
        if (recordDataManager == null) {
        	recordDataManager = new RecordDataManager(this);
        	recordDataManager.openDataBase();
        }
        Bundle bundle = new Bundle();
        bundle = this.getIntent().getExtras();
        String addtime = "";
        if(null!= bundle && null != bundle.getString("Addtime")){
        	addtime = bundle.getString("Addtime");
        }

        top_tbn_fanhui = (ImageButton)findViewById(R.id.nagivate_btn_left);
        top_tbn_xinzeng = (Button)findViewById(R.id.navigate_btn_right);
        title = (TextView)findViewById(R.id.title);
        navigate_btn_export = (Button)findViewById(R.id.navigate_btn_export);
        tv=(TextView)findViewById(R.id.tv);
        
        ExpandableListView listview=(ExpandableListView)findViewById(R.id.list);
//      listview.setGroupIndicator(null);//去掉默认左侧小图标
        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels ;
        //ExpandableListView箭头的位置变换
        listview.setIndicatorBounds(width-50, width);
        listview.setAdapter(new ListViewAdapter(this,recordDataManager,addtime));
        
        //设置监听返回按钮
        top_tbn_fanhui.setOnClickListener(mListener);
        SimpleDateFormat dateformat1=new SimpleDateFormat("yyyy-MM-dd");
        if(dateformat1.format(new Date()).equals(addtime)){
        	title.setText("今天");
        	top_tbn_xinzeng.setOnClickListener(mListener);
        }else{
        	title.setText("历史");
        	top_tbn_xinzeng.setVisibility(View.INVISIBLE);
        }
        navigate_btn_export.setOnClickListener(new Exporttxt());
        
        pd=new ProgressDialog(this);
        tv=new TextView(this);
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pd.setMessage("正在导出功过格到SD卡。。。");
        builder=new AlertDialog.Builder(this);
        builder.setTitle("导出数据");
        tv.setText(Html.fromHtml("<b>警告:</b>  本程序适用于将功过格导出为TXT文本至内存卡。"));
        tv.setMovementMethod(LinkMovementMethod.getInstance());  
 	}
	
	OnClickListener mListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.nagivate_btn_left:
				Intent counter = new Intent(TodayListNewActivity.this, HomeActivity.class);
				startActivity(counter);
				finish();
				break;
			case R.id.navigate_btn_right:
				int count=recordDataManager.findSeedsCount();
				if(count>0){
//					Intent intent2 = new Intent(TodayListNewActivity.this, SeedChooseActivity.class);
//					startActivity(intent2);
//					finish();
//					final String[] items = recordDataManager.fetchAllSeedNames();
//					Dialog alertDialog = new AlertDialog.Builder(TodayListNewActivity.this).setTitle("选择种子类型").setIcon(R.drawable.ic_launcher)
//							.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
//								@Override
//								public void onClick(DialogInterface dialog, int which) {
////									Toast.makeText(HomeActivity.this, ""+which+items[which], Toast.LENGTH_SHORT).show();  
//									Intent counter4 = new Intent(TodayListNewActivity.this, RecordAddActivity.class);
//									Bundle bundle = new Bundle(); 
//									bundle.putString("typename", items[which]);
//									counter4.putExtras(bundle); 
//									startActivity(counter4);
//								}
//							}).create();
//					alertDialog.setCanceledOnTouchOutside(false);//使除了dialog以外的地方不能被点击
//					alertDialog.show(); 
					Intent counter4 = new Intent(TodayListNewActivity.this, GridViewChooose.class);
					startActivity(counter4);
					finish();
				}else{
					Toast.makeText(TodayListNewActivity.this, R.string.type_empty,Toast.LENGTH_SHORT).show();
					return ;
				}
				break;
			}
		}
	};

	@Override
	public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
		return false;
	}
	
	@Override
	protected void onResume() {
		if (recordDataManager == null) {
			recordDataManager = new RecordDataManager(this);
			recordDataManager.openDataBase();
        }
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		if (recordDataManager != null) {
			recordDataManager.closeDataBase();
			recordDataManager = null;
        }
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		if (recordDataManager != null) {
			recordDataManager.closeDataBase();
			recordDataManager = null;
        }
		super.onPause();
	}
	
    class Exporttxt implements OnClickListener{
        
    	@Override
    	public void onClick(View v) {
    		// TODO Auto-generated method stub
    		c=Calendar.getInstance();
    		pd.show();
    		Thread thread=new Thread(new Runnable() {
	    		@Override
	    		public void run() {
	    			// TODO Auto-generated method stub
	    			String folderName="/sdcard/";
	    			String filename="功过格备份"+c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DAY_OF_MONTH)+"-"+c.get(Calendar.HOUR_OF_DAY)+"-"+c.get(Calendar.MINUTE)+"-"+c.get(Calendar.SECOND)+".txt";
	    			File file =null;
	    			file=new File(folderName+filename);
	    			if(!file.exists()){
	    				try {
	    					file.createNewFile();
	    				} catch (IOException e1) {
	    					// TODO Auto-generated catch block
	    					e1.printStackTrace();
	    				}
	    			}
	    			FileOutputStream fos=null;
		     
	    			try {
	    				fos=new FileOutputStream(file, true);
	    			} catch (FileNotFoundException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
//	    			ContentResolver cr=getContentResolver();
//	    			Cursor cursor=cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, "sort_key_alt");
//		     
//	    			while(cursor.moveToNext()){
//	    				String phoneNumber=null;
//	    				String name=cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
//	    				String id=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//	    				Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null); 
//	    				while(phone.moveToNext()){
//	    					phoneNumber=phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//	    				}
//	    				String geshi=name+"\t\t\t"+phoneNumber+"\n";
//	    				try {
//	    					fos.write(geshi.getBytes());
//	    				} catch (IOException e) {
//	    					// TODO Auto-generated catch block
//	    					e.printStackTrace();
//	    				}
//	    			}
	    			StringBuffer contentString = new StringBuffer();
	    			Cursor groupcursoCursor = recordDataManager.findRecord();
	    	        if(null != groupcursoCursor){
	    	            if(groupcursoCursor.moveToFirst() ){
	    	                do{
	    	                	String addtime = groupcursoCursor.getString(groupcursoCursor.getColumnIndex("add_time"));
	    	                	String addhour = groupcursoCursor.getString(groupcursoCursor.getColumnIndex("add_hour"));
	    	                	String addmin = groupcursoCursor.getString(groupcursoCursor.getColumnIndex("add_min"));
	    	                	String type_name = groupcursoCursor.getString(groupcursoCursor.getColumnIndex("type_name"));
	    	                	String type_id = groupcursoCursor.getString(groupcursoCursor.getColumnIndex("type_id"));
	    	                	
	    	                	contentString.append(addtime+" "+addhour+":"+addmin+"   种子类型："+type_name+"\r\n");
	    	                	
	    	    				Cursor cursor = recordDataManager.findRecordByTimeslot(addtime,addhour,addmin);
	    	    				if(cursor != null ){
    	    		               if( cursor.moveToFirst() ){
    	    		                   do{
    	    		   			        	String newcontent = cursor.getString(cursor.getColumnIndex("content"));
    	    		   			        	String contenttype = cursor.getString(cursor.getColumnIndex("contenttype"));
    	    		   			        	String newtype_id = cursor.getString(cursor.getColumnIndex("type_id"));
    	    		   			        	String titleString = "正    面:";
    	    		   			        	if(null != newtype_id && !"".equals(newtype_id)){
    	    		   			        		if(Integer.parseInt(newtype_id)==0){
		    	    		   			        	if(null != contenttype && !"".equals(contenttype)){
		    	    		   			        		if(Integer.parseInt(contenttype) == 1){
		    	    		   			        			titleString = "今日最好:";
		    	    		   		                	}else if (Integer.parseInt(contenttype) == 2) {
		    	    		   		                		titleString = "最需改进:";
		    	    		   		        			}else if (Integer.parseInt(contenttype) == 3) {
		    	    		   		        				titleString = "发    愿:";
		    	    		   		        			}
		    	    		   			        	}
    	    		   			        		}else{
    	    		   			        			if(null != contenttype && !"".equals(contenttype)){
		    	    		   			        		if(Integer.parseInt(contenttype)==1){
		    	    		   			        			titleString = "正    面:";
		    	    		   			        		}else if(Integer.parseInt(contenttype)==2){
		    	    		   			        			titleString = "负    面:";
		    	    		   			        		}else if(Integer.parseInt(contenttype)==3){
		    	    		   			        			titleString = "我    要:";
		    	    		   			        		}
		    	    		   			        	}
    	    		   			        		}
    	    		   			        	}
    	    		   			        	
    	    		   			        	contentString.append("  "+titleString+newcontent+"\r\n");
    	    		                   }while( cursor.moveToNext());
    	    		               }
    	    		            }
    	    		            cursor.close();
    	    		            contentString.append("\r\n");
	    	                }while( groupcursoCursor.moveToNext());
	    	            }
	    	        }
	    	        groupcursoCursor.close();
	    	        
	    	        try {
    					fos.write(contentString.toString().getBytes());
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
	    	        
	    			try {
	    				fos.close();
	    			} catch (IOException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
		     
		     
	    		}
    		});
    		thread.start();
    		pd.dismiss();
    		builder.setPositiveButton("确定", null);
    		builder.setMessage("功过格已经成功导出TXT文本，"+"\n\n"+"文件保存于SD卡根目录。");
    		ad=builder.create();
    		ad.show();
    	}
    }

}
